package com.ad.aidai.activitys.state;

import android.content.Context;

import com.ad.aidai.bean.Order;
import com.ad.aidai.common.ADApp;
import com.ad.aidai.common.RxBus;
import com.ad.aidai.common.utils.CheckUtil;
import com.ad.aidai.events.CommonEvent;
import com.ad.aidai.network.NetWork;
import com.ad.aidai.network.StatusCodeFromNet;
import com.ad.aidai.network.result.NetResult;
import com.orhanobut.logger.Logger;
import com.umeng.analytics.MobclickAgent;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import rx.Observable;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;

/**
 * StatePresenter
 * <p>
 * Created by Yusxon on 17/2/6.
 */

public class StatePresenter implements StateContract.Presenter {

    private Context mContext;
    private StateContract.View mView;
    private CompositeSubscription mSubscriptions;

    private List<String> imageUrls;

    private int imageCount = 0;

    private Order order;

    public StatePresenter(Context context, StateContract.View view) {
        this.mContext = context;
        this.mView = view;
        mView.setPresenter(this);
        imageUrls = new ArrayList<>();
        imageUrls.add("");
        imageUrls.add("");
        imageUrls.add("");
    }

    @Override
    public void subscribe() {
        mSubscriptions = new CompositeSubscription();
    }

    @Override
    public void unSubscribe() {
        mContext = null;
        mView = null;
        mSubscriptions.clear();
        mSubscriptions = null;
    }

    @Override
    public void loadOrder() {
        order = ADApp.getOrder();

        String[] orderType = {"代拿", "代买", "代办"};
        mView.showOrderType(orderType[order.getOrderType()]);
        mView.showOrderTime(order.getOrderSendTime());
        mView.showOrderContent(order.getOrderContent());
        mView.showOrderMoney(String.valueOf(order.getOrderReward()));
    }

    @Override
    public void deleteImage(int position) {
        imageCount--;
        imageUrls.remove(position);
        imageUrls.add("");
        mView.showStateImage(imageUrls.get(0), imageUrls.get(1), imageUrls.get(2));
    }

    @Override
    public void addImage(List<String> paths) {
        imageCount += paths.size();
        int position = 0;
        for (int i = 0; i < 3; ++i) {
            if (position < paths.size()) {
                if (CheckUtil.checkStrNull(imageUrls.get(i))) {
                    imageUrls.add(i, paths.get(position++));
                    imageUrls.remove(i + 1);
                }
            }
        }
        mView.showStateImage(imageUrls.get(0), imageUrls.get(1), imageUrls.get(2));
    }

    @Override
    public int getImageCount() {
        return imageCount;
    }

    @Override
    public String getImageUrl(int position) {
        return imageUrls.get(position);
    }

    private String getDateToString(long time) {
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        Date d = new Date(time);
        return sf.format(d);
    }

    public RequestBody createPartFromString(String descriptionString) {
        if (descriptionString == null) {
            descriptionString = "";
        }
        return RequestBody.create(
                MediaType.parse("multipart/form-data"), descriptionString);
    }

    @Override
    public void submit() {

        mView.showLoading();

        Map<String, RequestBody> pathMaps = new HashMap<>();
        Map<String, String> maps = new HashMap<>();
        maps.put("userId", String.valueOf(ADApp.getUser().getUserId()));
        maps.put("orderId", String.valueOf(order.getOrderId()));
        maps.put("stateCause", mView.getStateContent());
        maps.put("stateSubmitTime", getDateToString(System.currentTimeMillis()));

        for (String key : maps.keySet()) {
            pathMaps.put(key, createPartFromString(maps.get(key)));
        }

        File[] files = new File[imageCount];
        for (int i = 0; i < imageCount; ++i) {
            files[i] = new File(imageUrls.get(i));
        }
        MultipartBody.Part[] parts = new MultipartBody.Part[imageCount];
        for (int i = 0; i < imageCount; ++i) {
            RequestBody requestFile = RequestBody.create(MediaType.parse("image/jpeg"), files[i]);
            parts[i] = MultipartBody.Part.createFormData("fileData", files[i].getName(), requestFile);
        }

        Observable<NetResult> observable;

        try {
            if (imageCount == 0) {
                observable = NetWork.getOrderOperationApi()
                        .submitState(maps);
            } else {
                observable = NetWork.getOrderOperationApi()
                        .submitState(pathMaps, parts);
            }

            observable.subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Observer<NetResult>() {
                        @Override
                        public void onCompleted() {
                        }

                        @Override
                        public void onError(Throwable e) {
                            MobclickAgent.reportError(mContext, e);
                            Logger.t("ProfilePresenter").e(e.getMessage());
                            //关闭加载对话框
                            mView.closeLoading(false);
                        }

                        @Override
                        public void onNext(NetResult netResult) {
                            if (netResult.getCode() != StatusCodeFromNet.CODE_SUCCESS) {
                                Logger.t("ProfilePresenter").e(netResult.toString());
                                mView.closeLoading(false);
                                if (netResult.getCode() == StatusCodeFromNet.CODE_HAD_STATE) {
                                    mView.toast("已经申述过了,每个单只能申述一次");
                                    mView.exit();
                                }
                            } else {
                                //如果是我发的单
                                if (ADApp.getOrder().getSendUser().getUserId().equals(ADApp.getUser().getUserId())) {
                                    if(ADApp.getOrder().getOrderStatus() == Order.STATUS_RECIEVER_STATE) {
                                        ADApp.getOrder().setOrderStatus(Order.STATUS_STATE);
                                    } else {
                                        ADApp.getOrder().setOrderStatus(Order.STATUS_SENDER_STATE);
                                    }
                                } else {
                                    if(ADApp.getOrder().getOrderStatus() == Order.STATUS_SENDER_STATE) {
                                        ADApp.getOrder().setOrderStatus(Order.STATUS_STATE);
                                    } else {
                                        ADApp.getOrder().setOrderStatus(Order.STATUS_RECIEVER_STATE);
                                    }
                                }
                                RxBus.getInstance().postEvent(new CommonEvent<>(CommonEvent.ORDER_STATUS_CHANGE, ADApp.getOrder()));
                                mView.closeLoading(true);
                                mView.exit();
                            }
                        }
                    });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
